$(function(){
    $.fn.extend({
        selectControl:function(){
            return this.each(function(){
                var $box = SelectControl(this);
                var $input = $(this).children('input');
                $input.bind('click',focusHandler);
                return $(this);
            });
            
        },
        tableControl:function(){
            return this.each(function(){
                var $box = TableControl(this);
                var $input = $(this).children('input');
                $input.bind('click',focusHandler);
                return $(this);
            });
        }
    });
    function focusHandler(e){
        $(document).trigger('click');
        var $box = $('#select_'+$(this).attr('id'));
        var $input = $(this);
        $box.show();
        e.stopPropagation();
        $(document)[0].onclick = function(){
            $input.removeClass('focus');
            $box.hide();
        }
    }

    function SelectControl(container){
        var c = container;
        var w = c.offsetWidth;
        var h = c.offsetHeight;
        var sdata = $(c).attr('data');
        if( sdata.length == 0 ) return;
        var adata = sdata.length > 0 ? sdata.split(',') : [];
        var $select = $('<ul></ul>');
        $('body').append($select);
        $select.addClass("control");
        var $input = $($(c).children('input')[0]);
        $select.attr('id','select_'+$($(c).children('input')[0]).attr('id'));
        $select.width(w-2);
        $select[0].style.left = $(c).offset().left + 'px';
        $select[0].style.top = $(c).offset().top+h-2 + 'px';
        createListItems($select,adata,w,h);
        return $select;
    }
    function createListItems($select,adata,w,h){
        $select.empty();
        for( var i = 0 ; i < adata.length; i++ ){
            var $item = $('<li></li>');
            $select.append($item);
            $item.text(adata[i]);
            $item.addClass('item');
            $item.width(w-2);
            $item.height(h-2);
            $item.css('line-height',(h-2)+'px');
            $item.bind('click',clickHandler);
            $item.bind('mouseover',mouseoverHandler);
            $item.bind('mouseout',mouseoutHandler);
        }
    }
    var CmpayUI = window.CmpayUI || {};
    //下拉提示控件
    var SelectorControlUI = function(selector){
        $(selector).selectControl();
    }
    CmpayUI.selectControl = SelectorControlUI;
    /*
     *param:data{Array},下拉数据[1,2,4,5]
     */
    SelectorControlUI.setData =function(selector,data){
        var $select = $(selector);
        var $input = $($select.children('input')[0]);
        var $selectBox = $('#select_'+$($select.children('input')[0]).attr('id'));
        var w = $select[0].offsetWidth;
        var h = $select[0].offsetHeight;
        createListItems($selectBox,data,w,h);
    }


    function TableControl(container){
        var c = container;
        var w = c.offsetWidth;        
        var h = c.offsetHeight;
        var sdata = $(c).attr('data');
        if( sdata.length == 0 ) return;
        var adata = sdata.length > 0 ? sdata.split(',') : [];
        var $table = $('<div></div>');
        $('body').append($table);
        $table.addClass("control");
        $table.addClass("table");
        var $input = $($(c).children('input')[0]);
        $table.attr('id','select_'+$($(c).children('input')[0]).attr('id'));
        w = w - 2;
        h = h - 2;
        $table.width(w);
        $table[0].style.left = $(c).offset().left + 'px';
        $table[0].style.top = $(c).offset().top+h + 'px';
        return $table;
    }
    //下拉提示控件
    var TableControlUI = function(selector){
        $(selector).selectControl();
    }
    CmpayUI.tableControl = TableControlUI;
    /*
     *param:data{Array},下拉数据[1,2,4,5]
     */
    TableControlUI.setData =function(selector,data){
        var $select = $(selector);
        var $input = $($select.children('input')[0]);
        var $selectBox = $('#select_'+$($select.children('input')[0]).attr('id'));
        var w = $select[0].offsetWidth;
        var h = $select[0].offsetHeight;
        createTableItems($selectBox,data,w,h);
    }

    function createTableItems($table,adata,w,h){
        $table.empty();
        var t = w/3 , tt = t;
        var _version = navigator.appVersion;
        if( _version.indexOf('MSIE 6.0') > 0 || _version.indexOf('MSIE 7.0') > 0 ){ tt = Math.ceil(tt-2); }//IE67宽度计算
        for( var i = 0 ; i < adata.length; i++ ){
            var $item = $('<span></span>');
            $item.text(adata[i]);
            $item.addClass('item');
            $item.height(h);
            $item.css('line-height',h+'px');
            $item.css('width',t+'px');
            if( (i-1)%3 == 0 ) {
                $item.css('width',tt+'px');
                $item.addClass('col-border');
            }
            if( i > 2 && i < adata.length-3 ) $item.addClass('row-border');
            if(  i >= adata.length-3 ) $item.addClass('b-border');
            $item.bind('click',clickHandler);
            $item.bind('mouseover',mouseoverHandler);
            $item.bind('mouseout',mouseoutHandler);
            $table.append($item);
        }
    }

    function clickHandler(e){
        var id = $(this).parent().attr('id').replace(/^select_/,'');
        var $input = $('#'+id);
        $input.val($(this).text());
        $(this).parent().hide();
        e.stopPropagation();
    }

    function mouseoverHandler(e){
        $(this).addClass('hover');
        var id = $(this).parent().attr('id').replace(/^select_/,'');
        e.stopPropagation();
    }
    function mouseoutHandler(e){
        $(this).removeClass('hover');
        var id = $(this).parent().attr('id').replace(/^select_/,'');
        e.stopPropagation();
    }
});
$(function(){
    /*
     *输入错误与正确的插件,
     *如果想加上错误的提示，则直接使用$(selector).error('msg')
     *如果想加上正确的提示，则直接使用$(selector).right
     *错误提示，会在失去再次获取焦点时消失
     *正确提示，可以使用$(selector).removeRight();手动移除
     */
    $.fn.extend({
        error : function(msg){
            return this.each(function(){
                var $this = $(this);
                $this.addClass('error');
                createPane($this);
                $this.bind('focus',deletePane);
                return $this;
            });
            function createPane($this){
                var $pane = $('<div></div>');
                var $icon = $('<span></span>');
                var $text = $('<span></span>');
                $('body').append($pane);
                $pane.append($icon);
                $pane.append($text);
                $pane.attr('id','err_'+$this.attr('id'));
                $pane.addClass('tip-pane');
                $text.addClass('text');
                $icon.addClass('tip');
                $icon.addClass('error');
                $text.text(msg);
                $pane.width($this.parent()[0].offsetWidth-2);
                $pane.height($this.parent()[0].offsetHeight-2);
                $pane.css('line-height',$this.parent()[0].offsetHeight-2+'px');
                $pane.offset({left:$this.offset().left,top:($this.offset().top+$this.parent()[0].offsetHeight-2)});
            }
            function deletePane(){
                $(this).removeClass('error');
                $('#err_'+$(this).attr('id')).remove();
            }
        },
        right:function(){
            return this.each(function(){
                var $this = $(this);
                $this.addClass('right');
                createPane($this);
                return $this;    
            });
            function createPane($this){
                var $icon = $('<span></span>');
                $this.parent().append($icon);
                $icon.addClass('tip');
                $icon.addClass('right');
            }
            function deletePane(){
                $(this).removeClass('right');
                $(this).next().remove();
            }
        },
        removeRight:function(){
            return this.each(function(){
                $(this).removeClass('right');           
                $(this).next().remove();
                return $(this);
            });
        }
    });
    /*
     *占位符,在IE678的情况下模拟html5的palceholder的属性
     */
    $.fn.extend({
        placeholder:function(){
            return this.each(function(){
                var $this = $(this);
                var $label = $('<label></label>');
                $('body').append($label);
                $label.addClass('u-placeholder');
                var offset = $this.offset();
                $label.offset({left:offset.left + 11 , top:offset.top + 1});
                $label.width(this.offsetWidth - 43);
                $label.height(this.offsetHeight - 2);
                $label.css('line-height',this.offsetHeight - 2 + 'px');
                if( $.trim($this.val()).length <=0 ){
                    $label.text($this.attr('placeholder'));
                }
                $label.attr('for',$this.attr('id'));
                $label.attr('id',$this.attr('id')+'_placeholder');
                $label.bind('click',focusHandler);
                $this.bind('keyup',keyupHandler);
                //$this.bind('keydown',keydownHandler);
                $this.bind('propertychange',propertychangeHandler);
                return $this;
            });    
            function focusHandler(e){
                var id = $(this).attr('for');
                //$(this).hide();
                $('#'+id).trigger('focus');

            }
            function propertychangeHandler(e){
                switchLabel.apply(this,[e]);
            }
            function keydownHandler(e){
                $('#'+$(this).attr('id')+'_placeholder').hide();
            }
            
            function keyupHandler(e){
                switchLabel.apply(this,[e]);
            }
            function switchLabel(e){
                var v = $(this).val();
                if($.trim(v).length <= 0){
                    $('#'+$(this).attr('id')+'_placeholder').show();
                }else{
                    $('#'+$(this).attr('id')+'_placeholder').hide();
                }
            }
        } 
    });

    /*
     *
     *下拉选择控件,模拟浏览器原生的select标签
     */
    $.fn.extend({
        selection:function(){
            return this.each(function(){
                var $this = $(this);
                var $input = $($this.children('input')[0]);
                var $single = $($this.children('.single')[0]);
                var selection = createSelectionPane(this);
                $input.bind('click',inputFocusHandler);
                $single.bind('click',singleClickHandler);
                return $this;
            });
            function createSelectionPane(container){
                var c = container;
                var $this = $(c);
                var $input = $($this.children('input')[0]);
                var $vinput = $($this.children('input')[1]);
                var $select = $($this.children('.control')[0]);
                var $items = $select.children();
                var w = c.offsetWidth;
                var h = c.offsetHeight;
                $('body').append($select);
                $select.addClass("select");
                $select.attr('id','select_'+$($(c).children('input')[0]).attr('id'));
                $select.width(w-2);
                $select[0].style.left = $(c).offset().left + 'px';
                $select[0].style.top = $(c).offset().top+h-2 + 'px';
                for( var i = 0 ; i < $items.length; i++ ){
                    var $item = $($items[i]);
                    $item.addClass('item');
                    $item.width(w-2-parseInt($item.css('paddingLeft')));
                    $item.height(h-2);
                    $item.css('line-height',(h-2)+'px');
                    $item.bind('click',itemClickHandler);
                }
                return $select;
            }

            
            function singleClickHandler(e){
                var $this = $(this);
                var $input = $($(this).parent().children('input')[0]);
                var $single = $this;
                var $select = $('#select_'+$input.attr('id'));
                e.stopPropagation();
                if( !$single.hasClass('open') ){
                    $single.addClass('open');
                    $input.addClass('focus');
                    $('#select_'+$input.attr('id')).show();
                }else{
                    $single.removeClass('open');
                    $input.removeClass('focus');
                    $('#select_'+$input.attr('id')).hide();
                }
                 $(document)[0].onclick = function(){
                    $input.removeClass('focus');
                    $single.removeClass('open');
                    $select.hide();
                }
            }
            
            function inputFocusHandler(e){
                $(document).trigger('click');
                var $this = $(this);
                var $single = $($this.parent().children()[2]);
                var $select = $('#select_'+$this.attr('id'));
                e.stopPropagation();
                if( !$single.hasClass('open') ){
                    $single.addClass('open');
                    $this.addClass('focus');
                    $('#select_'+$this.attr('id')).show();
                }else{
                    $single.removeClass('open');
                    $this.removeClass('focus');
                    $('#select_'+$this.attr('id')).hide();
                }
                $(document)[0].onclick = function(){
                    $this.removeClass('focus');
                    $single.removeClass('open');
                    $select.hide();
                }
            };

           
            function itemClickHandler(e){
                var id = $(this).parent().attr('id').replace(/^select_/,'');
                var $input = $('#'+id);
                var $vinput = $('#real_'+id);
                $input.val($(this).text());
                $vinput.val($(this).attr('value'));
                $(this).parent().hide();
                $($input.parent().children('.single')[0]).removeClass('open');
                e.stopPropagation();
            }
        }         
    });
    /*
     *地区下拉选择控件
     */
    $.fn.extend({
        areaSelection:function(options){
            //var hotcity = [{id:'010',name:'北京',pinyin:'bei,jing'},{id:'020',name:'广州',pinyin:'guang,zhou'},{id:'0731',name:'长沙',pinyin:'chang,sha'},{id:'027',name:'武汉',pinyin:'wu,han'},{id:'0755',name:'深圳',pinyin:'shen,zhen'}];
            var _hotcity = [{id:'010',name:'北京'},{id:'020',name:'广州'},{id:'0731',name:'长沙'},{id:'027',name:'武汉'},{id:'0755',name:'深圳'}];
           
            var _cityMap = {HOT:_hotcity,AG:[],HN:[],OT:[],UZ:[]};
            var headerMap = {HOT:'热门城市',AG:'A-G',HN:'H-N',OT:'O-T',UZ:'U-Z'};
            var id_prev = 'areabox_';
            return this.each(function(){
                var hotcity = $.extend(true,[],_hotcity);
                var cityMap = $.extend(true,{},_cityMap);
                if( options ){
                    hotcity = $.extend(_hotcity,options.hotcity);
                }
                cityMap.HOT = hotcity;
                var $this = $(this);
                var $input = $($this.children('input')[0]);
                var $single = $($this.children('.single')[0]);
                createAreaBox(this,cityMap);
                $input.bind('click',inputFocusHandler);
                $single.bind('click',singleClickHandler);
                return $this;
                
            });
           
            
            function createAreaBox(container,cityMap){
                var c = container;
                var $input = $($(c).children('input')[0]);
                var id = id_prev+$input.attr('id');
                var w = c.offsetWidth;
                var h = c.offsetHeight;
                var offset = $(c).offset();
                var bw = $('body')[0].offsetWidth;
                var bh = $('body')[0].offsetHeight;
                var left = offset.left;
                var top = offset.top;
                var $box = $('<div></div>');
                $('body').append($box);
                $box.addClass('u-ui-citybox');
                $box.attr('id',id);
                left = (bw - (offset.left+w) < $box.width() ) ? offset.left+w - $box.width() : offset.left;
                top =  (bh - (offset.top + h) < $box.height() ) ? offset.top - $box.height() : offset.top + h;
                $box[0].style.left = left + 'px';
                $box[0].style.top = top-1 + 'px';
                createAreaInfo(cityMap);
                createAreaHeader($box,cityMap); 
                createAreaPane($box,cityMap['HOT']);
            }
            //创建地区选择盒子头部
            function createAreaHeader($box,cityMap){
                var $header = $('<ul></ul>');
                $box.append($header);
                $header.addClass('header');
                var i = 0;
                for( key in headerMap ){
                    var $item = $('<li></li>');
                    $header.append($item);
                    $item.text(headerMap[key]);
                    $item.attr('data-value',key);
                    $item.attr('data-index',i++);
                    $item.addClass('item');
                    $item.bind('click',function(e){
                        tabClickHandler.apply(this,[e,cityMap]);
                        
                    });
                }
                $($header.children()[0]).addClass('active');
                $($header.children()[0]).addClass('first');
                $header.attr('data-tab','0');
            }
            //创建地区选择盒子区域信息面板
            function createAreaPane($box,citys){
                var $pane = $('<div></div>');
                $box.append($pane);
                var $inner = $('<div></div>');
                $pane.append($inner);
                for( var i = 0 ; i < citys.length ; i++ ){
                    var city = citys[i];
                    var $item = $('<a href="javascript:;"></a>');
                    $inner.append($item);
                    $item.attr('id',city.id);
                    $item.text(city.name);
                    $item.attr('title',city.name);
                    $item.addClass('item');
                    $item.bind('click',cityItemClickHandler);
                    $item.bind('mouseover',function(){$(this).addClass('hover')}).bind('mouseout',function(){$(this).removeClass('hover')});
                }
                $pane.addClass('body');
                $inner.addClass('inner');
            }
            //创建区域信息
            function createAreaInfo(cityMap){
                var citys = window.CmpayUI.citys;
                for( var i = 0 ; i < citys.length ; i++ ){
                    var city = citys[i];
                    setCity2Map(city,cityMap);
                }
            }
            //初始化地区映射容器
            function setCity2Map(city,cityMap){
                var index = city.pinyin.substr(0,1);
                var map = {AG:'abcdefg',HN:'hijklmn',OT:'opqrst',UZ:'uvwxyz'};
                for( key in map ){
                    if( map[key].indexOf(index) > 0 ){
                        cityMap[key].push(city);
                        break;
                    }
                }
            }

            function tabClickHandler(e,cityMap){
                e.stopPropagation();
                var $this = $(this);
                var curIndex = $this.parent().attr('data-tab');
                if( curIndex == $this.attr('data-index') ) return true;
                var $box = $(this).parent().parent();
                var cityKey = $this.attr('data-value');
                var cityes = cityMap[cityKey];
                var areaPane = $this.parent().next();
                $this.addClass('active');
                var curTab = $this.parent().children()[$this.parent().attr('data-tab')];
                $(curTab).removeClass('active');
                $this.parent().attr('data-tab',$this.attr('data-index'));
                areaPane.remove();
                createAreaPane($box,cityes);
            }


            function singleClickHandler(e){
                var $this = $(this);
                var $input = $($(this).parent().children('input')[0]);
                var $single = $(this);
                var $box = $('#'+id_prev+$input.attr('id'));
                e.stopPropagation();
                if( !$single.hasClass('open') ){
                    $single.addClass('open');
                    $input.addClass('focus');
                    $('#'+id_prev+$input.attr('id')).show();
                }else{
                    $single.removeClass('open');
                    $input.removeClass('focus');
                    $('#'+id_prev+$input.attr('id')).hide();
                }
                $(document)[0].onclick = function(){
                    $input.removeClass('focus');
                    $single.removeClass('open');
                    $box.hide();
                }
            }
            
            function inputFocusHandler(e){
                $(document).trigger('click');
                var $this = $(this);
                var $single = $($this.parent().children()[2]);
                var $box = $('#'+id_prev+$this.attr('id'));
                e.stopPropagation();
                if( !$single.hasClass('open') ){
                    $single.addClass('open');
                    $this.addClass('focus');
                    $box.show();
                }else{
                    $single.removeClass('open');
                    $this.removeClass('focus');
                    $box.hide();
                }
                $(document)[0].onclick = function(){
                    $this.removeClass('focus');
                    $single.removeClass('open');
                    $box.hide();
                }
            };

           
            function cityItemClickHandler(e){
                var $this = $(this);
                var $box = $this.parent().parent().parent();
                var $input = $('#'+$box.attr('id').replace(id_prev,''));
                var $vinput = $input.next();
                var $single = $vinput.next();
                $vinput.val($this.attr('id'));
                $input.val($this.text());
                $input.removeClass('focus');
                $single.removeClass('open');
                $box.hide();
                e.stopPropagation(); 
            }
        }
    });
    $.fn.extend({
    /*
        bug:父层初始化为隐藏状态,则会导致盒子的位置发生错乱，要保证完全解决这个bug，
        需要不停的动态创建销毁box，对于这个bug的另外一个解决方法，
        是引导用户尽量不要在父层维隐藏状态下使用。
    */
        personbox:function(){
            return this.each(function(){
                var $this = $(this);
                createPersonBox(this);
                return $(this);
            });
            function createPersonBox(container){
                var c = container;
                var childs = $(c).children();
                var $input = $(childs[0]);
                var $personIcon = $(childs[1]);
                var $personbox = $(childs[2]);
                $('body').append($personbox);
                var iconOffset = $personIcon.offset();
                var left = iconOffset.left - $personbox.width()/2 + $personIcon.width()/2;
                var top = iconOffset.top + $personIcon.height() + 3;
                $personbox.offset({left:left,top:top});
                $personbox.attr('id','personbox_'+$input.attr('id'));
                $personIcon.bind('click',iconClickHandler);
                bindTabEvent($personbox);
                bindContentItemEvent($personbox);
            }
            function iconClickHandler(e){
                e.stopPropagation();
                var $this = $(this);
                var $c = $this.parent();
                var $input = $($c.children()[0]);
                var iconOffset = $this.offset();
                var $box = $('#personbox_'+$input.attr('id'));
                if( $this.attr('switch') != 'open' ){
                    /*
                    if( $this.attr('switch') != 'close' ){//防止隐藏
                        var left = iconOffset.left - $box.width()/2 + $this.width()/2;
                        var top = iconOffset.top + $this.height() + 3;
                        $box.offset({left:left,top:top});
                    }*/
                    $box.show();
                    $this.attr('switch','open');
                }else{
                    $this.attr('switch','close');
                    $box.hide();
                }
                $(document)[0].onclick = function(){
                    $input.removeClass('focus');
                    $box.hide();
                    $this.attr('switch','close');
                }
            }
            function bindTabEvent($box){
                var $tab = $box.find('.box-inner .box-tab');
                var $contents = $box.find('.box-inner .box-content');
                var $items = $tab.children();
                $($contents[$tab.attr('cur-index')]).show();
                $($items[$tab.attr('cur-index')]).addClass('active');
                $items.each(function(){
                    $(this).bind('click',tabEventHandler);        
                    $(this).bind('mouseover',tabMouseoverHandler);        
                    $(this).bind('mouseout',tabMouseoutHandler);        
                });
            }
            function tabMouseoverHandler(e){
                $(this).addClass('hover');
            }
            function tabMouseoutHandler(e){
                $(this).removeClass('hover');
            }
            function tabEventHandler(e){
                e.stopPropagation();
                var $this = $(this);
                var $boxInner = $this.parent().parent();
                var $contents = $boxInner.children('.box-content');
                var $tab = $this.parent();
                var $items = $tab.children();
                var index = $this.attr('data-index');
                var curIndex = $tab.attr('cur-index');
                if( curIndex == index ) return ;
                $($contents[curIndex]).hide();
                $($contents[index]).show();
                $($items[curIndex]).removeClass('active');
                $this.addClass('active');
                $tab.attr('cur-index',index);
            }
            function bindContentItemEvent($box){
                var $boxContent = $box.find('.box-content');
                $boxContent.each(function(){
                    var $items = $(this).children();       
                    $items.each(function(){
                        $(this).bind('click',contentItemClickHandler);    
                        $(this).bind('mouseover',contentItemMouseoverHandler);    
                        $(this).bind('mouseout',contentItemMouseoutHandler);    
                    });
                });
            }
            function contentItemClickHandler(e){
                e.stopPropagation();
                var $this = $(this);
                var $box = $this.parent().parent().parent();
                var $input = $('#'+$box.attr('id').replace('personbox_',''));
                var $icon = $input.next();
                var v = $this.attr('data-value');
                $this.parent().attr('cur-index',$this.attr('data-index'));
                $input.val(v);
                $box.hide();
                $icon.attr('switch','close');
            }
            function contentItemMouseoverHandler(){
                if( $(this).parent().attr('cur-index') == $(this).attr('data-index') ) return true;
                $(this).addClass('hover');
            }
            function contentItemMouseoutHandler(){
                if( $(this).parent().attr('cur-index') == $(this).attr('data-index') ) return true;
                $(this).removeClass('hover');
            }

        }       
    });

    function initPlaceHolder(){
        if(!$.support.leadingWhitespace){//如果ie678则添加placeholder
            var placeHolders = $('input[placeholder]');
            placeHolders.placeholder();
        }

    }
    initPlaceHolder();
});

$(function(){
    
});  
